import * as Koa from 'koa';
// 路由中间件
// import * as Router from 'koa-router';
// 静态资源中间件
import * as Static from 'koa-static';
// 编译页面中间件
import * as Views from 'koa-views';
// Body信息中间件
import * as bodyparser from 'koa-bodyparser';
// 跨域访问中间件
import * as cors from 'koa2-cors';
// 基础认证中间件
// import * as Auth from 'koa-basic-auth';
// Session中间件
// import * as Session from 'koa-session';
// 主路由
import { mainrouter } from './routers/mainrouter';
// import { aboutrouter } from './routers/restfulapis/about';
// const router = new Router();
const path = require('path');
const app = new Koa();
app.use(cors());
app.use(bodyparser());

// 访问调用前执行
app.use(async (ctx, next) => {
  await next();
});

// 访问后错误执行
app.use(async (ctx, next) => {
  await next();
  if (ctx.status === 404) {
    // ctx.response.redirect('/error');
    await ctx.render('error', {
      extension: 'html'
    });
  }
});

// 静态资源设置
app.use(Static(path.join(__dirname, 'www')));
// 页面设置
app.use(Views('www', {}));

// 路由设置
// router.use('/', mainrouter.routes(), mainrouter.allowedMethods());
// router.use('/api/about', aboutrouter.routes(), aboutrouter.allowedMethods());
app.use(mainrouter);

module.exports = app;
